package org.indi.yudidi;

import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.startup.Tomcat.FixContextListener;

public class EmbedTomcatHttp {
    static final int port = 9080;
    static final String docBase = "e:/tmp/tomcat";

    public static void main(String[] args) throws Exception {

        //YDD: 1. 初始化一个Tomcat. 端口,工作目录,禁用自动部署;
        Tomcat tomcat = new Tomcat();
        tomcat.setHostname("localhost");
        tomcat.setPort(port);
        tomcat.setBaseDir(docBase);
        tomcat.getHost().setAutoDeploy(false);

        //YDD: 2. 添加一个web项目到tomcat. StandardContext就代表一个web应用.
        String contextPath = "/book";
        StandardContext context = new StandardContext();
        context.setPath(contextPath);
        context.addLifecycleListener(new FixContextListener());//TODO
        tomcat.getHost().addChild(context);

        //YDD: 3. 相当于web.xml中给出servlet的mapping.
        String homeServlet = "homeServlet";
        tomcat.addServlet(contextPath, homeServlet, new HomeServlet());
        context.addServletMappingDecoded("/home", homeServlet);
        tomcat.start();
        tomcat.getServer().await();
    }
}
